package com.chzc.fm.duotin.ui.channel;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.chzc.fm.duotin.R;
import com.chzc.fm.duotin.adapter.recyclerview.HotAnLinearLayoutAdapter;
import com.chzc.fm.duotin.adapter.viewpager.CommImagePagerAdapter;
import com.chzc.fm.duotin.bean.channel.AnchorSpecial;
import com.chzc.fm.duotin.utils.DeviceUtil;
import com.chzc.fm.duotin.utils.DuotinTask;
import com.chzc.fm.duotin.utils.GlobalParam;
import com.chzc.fm.duotin.utils.HttpUtil;
import com.chzc.fm.duotin.utils.LogUtil;
import com.chzc.fm.duotin.widget.AnchorLayout;
import com.chzc.fm.duotin.widget.IndexView;
import com.chzc.fm.duotin.widget.ObservableScrollView;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by Administrator on 2016/6/24.
 */
public class AnchorActivity extends AppCompatActivity implements View.OnClickListener {

    private ViewPager viewPager;

    private TextView tvremtit,tvnewmore,tvrecommend,tvtypemore;

    private ImageView ivback;
    private IndexView guideView;

    private ObservableScrollView scrollView;

    private AnchorLayout anchorLayout;

    private AnchorLayout anchorLayouttype;

    private RecyclerView recyclerView;

    private boolean isrunning = true;

    private Handler handler = new Handler()
    {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            viewPager.setCurrentItem(viewPager.getCurrentItem()+1);

            if(isrunning){
                handler.sendEmptyMessageDelayed(0, 4000);
            }
        }
    };


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_anchor);

        handler.sendEmptyMessageDelayed(0, 4000);

        initViews();

        initdatas();

        initEvents();

    }

    public void initViews()
    {
        viewPager = (ViewPager) findViewById(R.id.anchor_recommend_vp);

        anchorLayout = (AnchorLayout) findViewById(R.id.anchor_conten_al);

        anchorLayouttype = (AnchorLayout) findViewById(R.id.anchor_contentyp_al);

        ivback = (ImageView) findViewById(R.id.anchor_back_iv);

        tvremtit= (TextView) findViewById(R.id.anchor_recommend_tit_tv);
        tvrecommend = (TextView) findViewById(R.id.anchor_recommend_tv);
        scrollView = (ObservableScrollView) findViewById(R.id.anchor_os);
        guideView = (IndexView) findViewById(R.id.anchor_guide_iv);
        recyclerView = (RecyclerView) findViewById(R.id.anchor_hot_rl);
        tvnewmore = (TextView) findViewById(R.id.anchor_more_tv);
        tvtypemore = (TextView) findViewById(R.id.anchor_typemore_tv);

        LinearLayoutManager manager  = new LinearLayoutManager(getApplicationContext());
        manager.setOrientation(LinearLayoutManager.VERTICAL);
        recyclerView.setLayoutManager(manager);

        ivback.setOnClickListener(this);
        tvnewmore.setOnClickListener(this);
        tvtypemore.setOnClickListener(this);

    }

    public void initEvents()
    {
        scrollView.setScrollViewListener(new ObservableScrollView.ScrollViewListener() {
            @Override
            public void onScrollChanged(ObservableScrollView scrollView, int x, int y, int oldx, int oldy) {

                int dpy = DeviceUtil.px2dip(AnchorActivity.this,y);

                if(dpy>155 && dpy<500)
                {
                    tvrecommend.setText("新晋主播");
                }else if(dpy>500)
                {
                    tvrecommend.setText("火热主播");
                }else if (dpy<155)
                {
                    tvrecommend.setText("热门推荐");
                }

                LogUtil.w("y = "+ DeviceUtil.px2dip(AnchorActivity.this,y));
            }
        });
    }


    public void initdatas()
    {
        getAnchor(new DuotinTask.IRequestCallback() {
            @Override
            public void success(Object object) {

                try {

                    LogUtil.w("开始解析数据");

                    //解析
                    JSONObject root = new JSONObject(object.toString());

                    String error_msg = root.getString("error_msg");

                    if("SUCCESS".equals(error_msg))
                    {
                        JSONObject data = root.getJSONObject("data");

                        showBanner(data);

                        showNew(data);

                        showType(data);

                        showHot(data);
                    }


                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void error(String msg) {

            }
        });
    }

    /**
     * 显示banner视图
     */
    public void showBanner(JSONObject data) throws JSONException {

        JSONArray bannerlist =  data.getJSONArray("banner_recommend");

        final List<AnchorSpecial> specialList = AnchorSpecial.arrayAnchorSpecialFromData(bannerlist.toString());

        LogUtil.w("specialList.size() = " + specialList.size());

        //获取图片url和ImageView的集合
        final List<ImageView> imageViews = new ArrayList<>();
        List<String> urls = new ArrayList<>();

        for (int i = 0 ; i < specialList.size() ; i++)
        {
            AnchorSpecial anchorSpecial = specialList.get(i);

            ImageView imageView = new ImageView(getApplicationContext());
            imageView.setScaleType(ImageView.ScaleType.FIT_XY);

            imageViews.add(imageView);

            urls.add(anchorSpecial.getImage_url());


        }

        CommImagePagerAdapter adapter = new CommImagePagerAdapter(imageViews,urls);
        viewPager.setAdapter(adapter);

        viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {

                tvremtit.setText(specialList.get(position%imageViews.size()).getTitle());
                guideView.setCurrIndex(position%imageViews.size());
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
    }

    /**
     * 显示新晋主播
     */
    public void showNew(JSONObject data) throws JSONException
    {
        JSONArray  newlist = data.getJSONArray("new_albums");

        List<AnchorSpecial> specialList = AnchorSpecial.arrayAnchorSpecialFromData(newlist.toString());

        LogUtil.w("specialList.size() >>>>> " + specialList.size());

        anchorLayout.setSpecialList(specialList);
    }

    /**
     * 显示分类金榜
     * @param data
     * @throws JSONException
     */
    public void showType(JSONObject data) throws JSONException
    {
        JSONArray typelist = data.getJSONArray("hot_ranks");
        List<AnchorSpecial> specialList = AnchorSpecial.arrayAnchorSpecialFromData(typelist.toString());
        anchorLayouttype.setSpecialList(specialList);

    }


    /**
     * 显示火热主播
     * @param data
     * @throws JSONException
     */
    public void showHot(JSONObject data) throws JSONException {

        JSONObject hot = data.getJSONObject("hot_albums");

        JSONArray hotlist = hot.getJSONArray("data_list");

        List<AnchorSpecial> specialList = AnchorSpecial.arrayAnchorSpecialFromData(hotlist.toString());

        HotAnLinearLayoutAdapter hotAdapter = new HotAnLinearLayoutAdapter(getApplicationContext(),specialList);
        recyclerView.setAdapter(hotAdapter);
        hotAdapter.setOnItemClickListener(new HotAnLinearLayoutAdapter.mOnItemClickListener() {
            @Override
            public void OnItemClick(int position) {

            }
        });

    }



    /**
     *  请求频道模块的主播电台数据
     * @param requestCallback
     */
    public static void getAnchor(DuotinTask.IRequestCallback requestCallback)
    {
        DuotinTask.IRequest request = new DuotinTask.IRequest() {
            @Override
            public Object doRequest() {

                return HttpUtil.doGet(GlobalParam.URL_ANCHOR);
            }
        };

        new DuotinTask(request,requestCallback).execute();
    }





    @Override
    public void onClick(View v) {

        Intent intent = null;
        switch (v.getId())
        {
            case R.id.anchor_back_iv:
                finish();
                break;
            //分类精榜更多点击事件
            case R.id.anchor_typemore_tv:
                Toast.makeText(AnchorActivity.this,"你点击了分类更多按钮",Toast.LENGTH_SHORT).show();
                intent = new Intent(AnchorActivity.this,TypeAnchorActivity.class);
                startActivity(intent);
                break;
            //新晋主播更多点击事件
            case R.id.anchor_more_tv:
                Toast.makeText(AnchorActivity.this,"你点击了新晋主播更多按钮",Toast.LENGTH_SHORT).show();
                intent = new Intent(AnchorActivity.this,NewAnchorActivity.class);
                startActivity(intent);
                break;
        }
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        isrunning = false;
    }
}
